﻿using DevExpress.Data;
using DevExpress.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Timesheet.Domain;
using Timesheet.Service;
/*
 * status  //0;open;1;coord pending;2; mrg pending;3;closed
 */
namespace Timesheet.WebForm.TimeSheets
{
    public partial class Lines : System.Web.UI.Page
    {
        #region Var
        public ITimeSheetDetailsService _Service { get; set; }
        public IUserService _UserService { get; set; }
        public IProjectService _PrjService { get; set; }
        public ILocationsService _LocService { get; set; }
        public IDisciplinesService _DiciplineService { get; set; }
        public IGroupsService _GroupService { get; set; }
        public IClassCodesService _ClassCodeService { get; set; }
        public ITimeSheetsService _TmshService { get; set; }
        public ITeamService _TeamService { get; set; }
        public ITeamDetailService _TeamDetailService { get; set; }
        public IPrjReferencesService _PrjReferencesService { get; set; }

        private Timesheet.Domain.TimeSheets _currentTmsh = null;

        Dictionary<string, string> status = new Dictionary<string, string>(){
            {"-1","" },
            {"0","Open" },
            {"1","Coordinator pending" },
            {"2","Manager Pending" },
            {"3","Closed" }
        };
        Dictionary<DayOfWeek, string> dateWeekMaps = new Dictionary<DayOfWeek, string>(){
            {DayOfWeek.Sunday,"colSun" },
            {DayOfWeek.Monday,"colMon" },
            {DayOfWeek.Tuesday,"colTue" },
            {DayOfWeek.Wednesday,"colWeb" },
            {DayOfWeek.Thursday,"colThu" },
            {DayOfWeek.Friday,"colFri" },
            {DayOfWeek.Saturday,"colSat" }            
        };
        bool canEdit = true;
        long tmshID = -1;
        #endregion

        #region  Loading
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["tmshID"] + "" == "")
            {
                btnApprove.Visible = btnNewTmsh.Visible = btnReport.Visible = false;
                Response.Redirect("~/Account/Login.aspx");
                return;
            }

            if (!IsPostBack)
            {
                btnApprove.Visible = false;
                btnNewTmsh.Visible = false;

                tmshID = Convert.ToInt64(Request.Params["tmshID"]);
                var _currentTmsh = _TmshService.GetByID(tmshID);

                if (_currentTmsh != null)
                {
                    #region Check Week Visble
                    int totalWidthOTST = 7 * 40;
                    for (DateTime i = _currentTmsh.From; i <= _currentTmsh.To; i = i.AddDays(1))
                    {
                        totalWidthOTST -= 40;
                        grvTmshDetails.Columns[dateWeekMaps[i.DayOfWeek]].Visible = true;
                        grvTmshDetails.Columns[dateWeekMaps[i.DayOfWeek]].Caption = i.DayOfWeek.ToString().Substring(0, 3).ToUpper() + i.ToString(" MM/dd");
                    }
                    int width = (int)grvTmshDetails.Width.Value - totalWidthOTST;
                    grvTmshDetails.Width = new Unit(grvTmshDetails.Width.Value - totalWidthOTST);

                    #endregion

                    #region Get project info

                    var project = _PrjService.GetByID(_currentTmsh.ProjectID);
                    var teams = _TeamService.GetByID(_currentTmsh.TeamID);
                    string sCoordinators = "";
                    string sTeamName = "";
                    string sJobLocation = "";
                    string sDicipline = "";
                    string sTeamLeads = "";

                    if (project != null)
                    {
                        lblPrjName.Text = project.ProjectName;
                        lblCustomer.Text = project.CustomerInfo;
                        lblJob.Text = project.JobInfo;
                        lblJobDescription.Text = project.JobDes;
                        lblContact.Text = project.Contact;
                        lblNetwork.Text = project.NetCode;
                        lblResp.Text = project.ResponsePerson;
                        lblTicker.Text = project.JobInfo + "-" + _currentTmsh.Ticket;
                        lblWbs.Text = project.Wbs;
                    }
                    #endregion

                    #region time sheet info

                    lblStatus.Text = status[_currentTmsh.Status];
                    lblWeek.Text = _currentTmsh.Week;
                    sTeamName = teams.TeamName;
                    
                    List<TeamDetail> teamDetails = new List<TeamDetail>();
                    
                    var iTeamMembers = _TeamDetailService.GetTeamDetails(teams.Id);
                    teamDetails.AddRange(iTeamMembers);
                    
                    foreach (var item in teamDetails)
                    {
                        var user = _UserService.GetUserById(item.EmployerID);
                        if (user != null)
                        {
                            if (user.TeamLead)
                                sTeamLeads += (sTeamLeads == "" ? "" : ", ") + user.LastName;                            
                        }
                    }

                    //var locs = _PrjReferencesService.GetPrjReferences("1", _currentTmsh.ProjectID);//Location
                    //var dicips = _DiciplineService.GetByPrjID(_currentTmsh.ProjectID);//Dicipline

                    //if (locs != null)
                    //    sJobLocation = string.Join(",", locs.Select(x => x.RefNames));
                    //if (dicips != null)
                    //    sDicipline = string.Join(",", dicips.Select(x => x.DisciplineName));

                    var location = _LocService.GetByID(teams.LocationID);
                    if(location != null)
                        sJobLocation = location.LocationName;
                    var dicipline = _DiciplineService.GetByID(teams.DesciplineID);
                    if(dicipline != null)
                        sDicipline = dicipline.DisciplineName;

                    var refObj = _PrjReferencesService.GetPrjReferences("2", _currentTmsh.ProjectID);;
                    if(refObj!= null){
                        foreach (var item in refObj)
                        {
                            var user = _UserService.GetUserById(item.RefID);
                            if (user != null)
                            {
                                sCoordinators += (sCoordinators == "" ? "" : ", ") +user.LastName;                                                          
                            }
                        }                        
                    }

                    lblCoordID.Text = sCoordinators;
                    lblTeamName.Text = sTeamName;
                    lblTeamLeads.Text = sTeamLeads;
                    lblLocation.Text = sJobLocation;
                    lblDiscipline.Text = sDicipline;
                    
                    var appUser = _UserService.GetUserById(_currentTmsh.ApprovedBy);
                    if(appUser!=null)
                        lblApproved.Text =  appUser.FullName;

                    #endregion

                    #region apply permisson button
                    string role = Session["userrole"] + "";

                    var col = grvTmshDetails.Columns["colAction"] as GridViewCommandColumn;
                    var userInfo = (User)Session["User"];
                    if(userInfo==null)
                    {
                        Response.Redirect("~/Account/Login.aspx");
                        return;
                    }
                    if (_currentTmsh.Status == "0" )
                    {
                        if (userInfo.TeamLead || userInfo.Coordinator)
                        {
                            btnApprove.Visible = true;
                            btnNewTmsh.Visible = true;
                            if (col != null)
                            {
                                col.ShowEditButton = canEdit;
                                col.ShowDeleteButton = canEdit;
                            }
                        }
                    }
                    else if (_currentTmsh.Status == "1")
                    {
                        if (userInfo.TeamLead)
                        {
                            btnNewTmsh.Visible = true;
                            col.ShowEditButton = false;
                            col.ShowDeleteButton = false;
                        }
                        if (userInfo.Coordinator)
                        {
                            btnNewTmsh.Visible = true;
                            btnApprove.Visible = true;
                            if (col != null)
                            {
                                col.ShowEditButton = canEdit;
                                col.ShowDeleteButton = canEdit;
                            }
                        }
                    }
                    else if (_currentTmsh.Status == "2")
                    {
                        if (userInfo.TeamLead)
                        {
                            btnNewTmsh.Visible = true;
                            col.ShowEditButton = false;
                            col.ShowDeleteButton = false;
                        }
                        if (userInfo.Coordinator)
                        {
                            btnNewTmsh.Visible = true;
                            btnApprove.Visible = false;
                            if (col != null)
                            {
                                col.ShowEditButton = false;
                                col.ShowDeleteButton = false;
                            }
                        }
                        if (userInfo.Manager)
                        {
                            btnApprove.Visible = true;
                            if (col != null)
                            {
                                col.ShowEditButton = true;
                                col.ShowDeleteButton = true;
                            }
                        }
                    }
                    else
                    {
                        if (userInfo.TeamLead || userInfo.Coordinator)
                        {
                            btnNewTmsh.Visible = true;
                        }
                        if (col != null)
                        {
                            col.ShowEditButton = false;
                            col.ShowDeleteButton = false;
                        }
                    }

                    if (col != null && col.ShowEditButton == false)
                    {
                        col.Visible = false;
                        grvTmshDetails.Width = new Unit(grvTmshDetails.Width.Value - 130);
                        width = width - 130;
                    }

                    if (grvTmshDetails.Width.Value > 1125)
                    {
                        Site myMasterPage = Page.Master as Site;
                        myMasterPage._MainPanel.Width = width + 38;
                    }
                    else
                    {
                        Site myMasterPage = Page.Master as Site;
                        myMasterPage._MainPanel.Width = 1099;
                    }
                    
                    #endregion
                }
                
            }
        }

        #endregion

        #region btn click

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            var userInfo = (User)Session["User"];
            _currentTmsh = _TmshService.GetByID(Convert.ToInt64(Request.Params["tmshID"]));

            if (_currentTmsh == null)
                return;
            if (userInfo == null)
                return;
            if (userInfo.TeamLead)
            {
                List<User> coods = _UserService.GetActivedCoodinators(_currentTmsh.ProjectID);
                if (coods == null || coods.Count == 0)
                    _currentTmsh.Status = "2";
                else 
                    _currentTmsh.Status = "1";
            }
            if (userInfo.Coordinator)
                _currentTmsh.Status = "2";
            if (userInfo.Manager)
                _currentTmsh.Status = "3";
            _currentTmsh.ApprovedBy = userInfo.Id;
            _TmshService.Update(_currentTmsh);

            lblStatus.Text = status[_currentTmsh.Status];
            lblApproved.Text = userInfo.FullName;
            btnApprove.Visible = false;
        }

        protected void btnCreatetmsh_Click(object sender, EventArgs e)
        {
             _currentTmsh = _TmshService.GetByID(Convert.ToInt64(Request.Params["tmshID"]));
            Response.Redirect("New.aspx?prjID=" + _currentTmsh.ProjectID+"&team="+ _currentTmsh.TeamID+"&tmsh="+_currentTmsh.Id+"&date="+ _currentTmsh.To.AddDays(1));
            //grvTmshDetails.AddNewRow();
        }

        protected void btnCreateReport_Click(object sender, EventArgs e)
        {
            //var _currentTmsh = _TmshService.GetByID(Convert.ToInt64(Request.Params["tmshID"]));
            //Response.Redirect("~/Report/report.aspx?prjID=" + _currentTmsh.ProjectID);
            Response.Redirect("~/Report/report.aspx?tmshID=" + Convert.ToInt64(Request.Params["tmshID"]));
        }
        #endregion

        #region datasource event
        protected void dsTmshDetails_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = _Service;
        }

        protected void dsEmployers_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = _UserService;
        }

        protected void dsGroups_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = _GroupService;
        }

        protected void dsClassCodes_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = _ClassCodeService;
        }

        protected void grvTmshDetails_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            e.NewValues["TransID"] = Request.Params["tmshID"];
        }

        protected void grvTmshDetails_CustomUnboundColumnData(object sender, ASPxGridViewColumnDataEventArgs e)
        {
            //"[MonSTHours] + [TueSTHours] + [WebSTHours] + [ThuSTHours]+[FriSTHours]+[SatSTHours] +[SunSTHours]"
            //"[MonOTHours] + [TueOTHours] + [WebOTHours] + [ThuOTHours]+[FirOTHours]+[SatOTHours] +[SunOTHours]"

            if (e.Column.FieldName == "SumST")
            {
                Decimal value = Convert.ToDecimal(e.GetListSourceFieldValue("MonSTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("TueSTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("WebSTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("ThuSTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("FriSTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("SatSTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("SunSTHours"));

                e.Value = value;
            }
            else if (e.Column.FieldName == "SumOT")
            {
                Decimal value = Convert.ToDecimal(e.GetListSourceFieldValue("MonOTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("TueOTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("WebOTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("ThuOTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("FirOTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("SatOTHours"));
                value += Convert.ToDecimal(e.GetListSourceFieldValue("SunOTHours"));

                e.Value = value;
            }
        }
        #endregion

        protected void grvTmshDetails_RowUpdating(object sender,DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
             e.NewValues["TransID"] = Request.Params["tmshID"];
        }

        protected void grvTmshDetails_CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e)
        {
            if (e.Column.Caption == "No") {
                e.DisplayText = (e.VisibleRowIndex  + 1).ToString();
            }

            if (e.Column.FieldName == "MonSTHours" || e.Column.FieldName == "MonOTHours" || e.Column.FieldName == "TueOTHours" || e.Column.FieldName == "TueSTHours" ||
                e.Column.FieldName == "WebOTHours" || e.Column.FieldName == "WebSTHours" || e.Column.FieldName == "ThuOTHours" || e.Column.FieldName == "ThuSTHours" ||
                e.Column.FieldName == "FirOTHours" || e.Column.FieldName == "FriSTHours" || e.Column.FieldName == "SatOTHours" || e.Column.FieldName == "SatSTHours" ||
                e.Column.FieldName == "SunSTHours" || e.Column.FieldName == "SunOTHours")
            {
                if (e.Value == null )
                    e.DisplayText = "";
                else
                {
                    Decimal value = 0;
                    Decimal.TryParse(e.Value.ToString(), out value);
                    if (value == 0)
                        e.DisplayText = "";
                }
            }

            if (e.Column.FieldName == "TotalST" || e.Column.FieldName == "TotalOT")
            {
                if (e.Value == null)
                    e.DisplayText = "-";
                else
                {
                    Decimal value = 0;
                    Decimal.TryParse(e.Value.ToString(), out value);
                    if (value == 0)
                        e.DisplayText = "-";
                }
            }
        
        }

        decimal totalSumUnitsInStock;

        protected void grvTmshDetails_CustomSummaryCalculate(object sender, DevExpress.Data.CustomSummaryEventArgs e)
        {
            string summaryTAG = (e.Item as ASPxSummaryItem).Tag;
            if (e.SummaryProcess == CustomSummaryProcess.Start)
            {
                totalSumUnitsInStock = 0;
            }
            if (e.SummaryProcess == CustomSummaryProcess.Calculate)
            {
                decimal value = 0;
                object temp = e.GetValue("Mileage");
                if (temp == null)
                    value = 0;
                else 
                    Decimal.TryParse(temp.ToString(), out  value);

                totalSumUnitsInStock += value;
            }
            if (e.SummaryProcess == CustomSummaryProcess.Finalize)
            {
                switch (summaryTAG)
                {
                    case "Item_A":
                        e.TotalValue = totalSumUnitsInStock;
                        break;
                    
                }
            }
        }

        protected void grvNoteDetails_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            e.NewValues["timeSheetDetailsId"] = Convert.ToInt64(Session["timeSheetDetailsId"]);
        }

        protected void grvNoteDetails_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            e.NewValues["timeSheetDetailsId"] = Convert.ToInt64(Session["timeSheetDetailsId"]);
        }

        protected void grvNoteDetails_BeforePerformDataSelect(object sender, EventArgs e)
        {
            Session["timeSheetDetailsId"] = (sender as ASPxGridView).GetMasterRowKeyValue();
        }
        protected void grvNoteDetails_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
        {
            ASPxGridView grvNoteDetails = sender as ASPxGridView;
            if (grvNoteDetails.VisibleRowCount >= 1)
            {
                if (e.ButtonType == DevExpress.Web.ColumnCommandButtonType.New)
                    e.Visible = false;
            }
            else
            {
                if (e.VisibleIndex == -1 || e.VisibleIndex == 0) return;
            }
            
            
        }
    }
}